package com.sleep.satokendemo.util;

import lombok.experimental.UtilityClass;
import org.springframework.stereotype.Component;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.function.Function;
import java.util.function.Supplier;


public class FieldUtil {

    public static  <R> String getFieldName(SFunction<R> supplier) {
        SerializedLambda serializedLambda = getSerializedLambda(supplier);
        if (serializedLambda != null) {
            String methodName = serializedLambda.getImplMethodName();
            if (methodName.startsWith("get")) {
                return methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
            }else {
                throw new RuntimeException("方法名必须以get开头");
            }
        }else {
            throw new RuntimeException("属性名不存在");
        }
    }

    private static  <R> SerializedLambda getSerializedLambda(SFunction<R> supplier)  {
        try {
            Method method = supplier.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(true);
            return (SerializedLambda) method.invoke(supplier);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
